package com.ywy.controller;

import com.ywy.config.ApplicationInitialize;
import com.ywy.entity.Comment;
import com.ywy.entity.Res;
import com.ywy.entity.ResType;
import com.ywy.entity.User;
import com.ywy.lucene.ResIndex;
import com.ywy.service.CommentService;
import com.ywy.service.ResService;
import com.ywy.utils.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资源Controller
 *
 * @author ywy
 * @date 2022/8/25 10:05
 */
@Controller
@RequestMapping("res")
public class ResController {
    @Resource
    private ResService resService;
    @Resource
    private CommentService commentService;

    @Resource
    private ResIndex resIndex;

    @Value("${system.resImagePath}")
    private String resImagePath;

    @Resource
    private RedisUtil<Res> redisUtil;

    /**
     * 分页查询资源信息
     *
     * @param pageNo
     * @param typeId
     * @param session
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(@RequestParam(defaultValue = "1") Integer pageNo, @RequestParam(required = false) Integer typeId, HttpSession session) {
        // 分页查询资源信息
        Res res = new Res();
        res.setCheckStatus(2); // 审核通过
        if (typeId != null) {
            ResType resType = ApplicationInitialize.resTypeMap.get(typeId);
            res.setResType(resType);
            session.setAttribute("typeId", "t_" + typeId);
        }
        List<Res> resList = resService.list(res, pageNo, 20);
        Long total = resService.getTotal(res);

        StringBuffer param = new StringBuffer();
        if (typeId != null) {
            param.append("&typeId=" + typeId);
        }

        // 热门资源
        res.setHot(true);
        List<Res> hotResList = resService.list(res, 1, 40);

        ModelAndView mav = new ModelAndView();
        mav.addObject("resList", resList);
        mav.addObject("pageCode", PageUtil.genPagination("/res/list", total, pageNo, 20, param.toString()));
        mav.addObject("hotResList", hotResList);
        mav.setViewName("index");

        return mav;
    }

    /**
     * 根据id查询资源详细信息
     *
     * @param id
     * @return
     */
    @RequestMapping("detail/{id}")
    public ModelAndView detail(@PathVariable("id") Integer id) {
        // 根据id查询资源详细信息
        Res res = resService.getByIdFromCache(id);

        // 热门资源
        Res resQuery = new Res();
        resQuery.setResType(res.getResType());
        resQuery.setHot(true);
        List<Res> hotResList = resService.listFromCache(resQuery, 1, 40);

        // 评论数量
        Comment comment = new Comment();
        comment.setRes(res);
        comment.setStatus(1); // 审核通过的评论信息

        ModelAndView mav = new ModelAndView();
        mav.addObject("res", res);
        mav.addObject("hotResList", hotResList);
        mav.addObject("commentCount", commentService.getTotal(comment));
        mav.setViewName("res/detail");
        return mav;
    }

    /**
     * 搜索资源
     * @param q
     * @param pageNo
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("search")
    public ModelAndView search(String q, @RequestParam(defaultValue = "1") Integer pageNo, HttpSession session) throws Exception {
        session.setAttribute("typeId", "t_0");

        // lucene搜索资源
        List<Res> resList = resIndex.search(q);
        Integer toIndex = resList.size() >= pageNo * 10 ? pageNo * 10 :resList.size();

        // 热门资源
        Res res = new Res();
        res.setCheckStatus(2); // 审核通过
        res.setHot(true);
        List<Res> hotResList = resService.list(res, 1, 40);

        ModelAndView mav = new ModelAndView();
        mav.addObject("q", q);
        mav.addObject("resList", resList.subList((pageNo - 1) * 10, toIndex));
        mav.addObject("resultTotal", resList.size());
        mav.addObject("hotResList", hotResList);
        mav.addObject("pageCode", PageUtil.genUpAndDownPageCode(q, Long.valueOf(resList.size()), pageNo, 10));
        mav.setViewName("res/result");
        return mav;
    }

    /**
     * 添加资源
     *
     * @param res
     * @param session
     * @return
     */
    @RequestMapping("add")
    public ModelAndView add(Res res, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        res.setPublishDate(new Date());
        res.setUser(user);
        res.setCheckStatus(1);
        res.setView(0);
        resService.save(res);

        ModelAndView mav = new ModelAndView();
        mav.setViewName("res/publicSuccess");
        return mav;
    }

    /**
     * 跳转到资源修改页面
     * @return
     */
    @RequestMapping("edit/{id}")
    public ModelAndView edit(@PathVariable("id") Integer id) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("res", resService.getById(id));
        mav.setViewName("res/edit");
        return mav;
    }

    /**
     * 更新资源
     *
     * @param res
     * @return
     */
    @RequestMapping("update")
    public ModelAndView update(Res res) {
        Res oldRes = resService.getById(res.getId());
        oldRes.setName(res.getName());
        oldRes.setResType(res.getResType());
        oldRes.setContent(res.getContent());
        oldRes.setDownloadUrl(res.getDownloadUrl());
        oldRes.setDownloadPass(res.getDownloadPass());
        oldRes.setPoints(res.getPoints());
        // 假如审核未通过，用户点击修改的话，则重新审核
        if (oldRes.getCheckStatus() == 3) {
            // 更新资源索引
            oldRes.setCheckStatus(1);
        }
        resService.save(oldRes);

        ModelAndView mav = new ModelAndView();
        mav.setViewName("res/editSuccess");
        return mav;
    }

    /**
     * 上传资源图片
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("uploadImage")
    public Map<String, Object> uploadImage(MultipartFile file) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename(); // 获取文件名
            String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 获取文件的后缀
            String newFileName = DateUtil.formatDatePure() + suffixName; // 新文件名
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(resImagePath + DateUtil.formatDateSlash() + newFileName));

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("src", "/resImages/" + DateUtil.formatDateSlash() + newFileName);
            dataMap.put("title", newFileName);

            map.put("code", 0);
            map.put("msg", "上传成功");
            map.put("data", dataMap);
        }
        return map;
    }

    /**
     * 根据条件分页查询用户资源信息
     *
     * @param res
     * @param page
     * @param limit
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("userResList")
    public Map<String, Object> userResList(Res res, Integer page, Integer limit, HttpSession session) {
        // 查询用户资源信息
        User user = (User) session.getAttribute("currentUser");
        res.setUser(user);
        List<Res> resList = resService.list(res, page, limit);
        Long count = resService.getTotal(res);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("count", count);
        resultMap.put("data", resList);
        return resultMap;
    }

    /**
     * 加载相关资源
     * @param q
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("loadRelatedResources")
    public List<Res> loadRelatedResources(String q) throws Exception {
        if (StringUtil.isEmpty(q)) {
            return null;
        }
        return resIndex.searchNoHighLighter(q);
    }

    /**
     * 根据id删除资源
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public Map<String, Object> delete(Integer id) {
        resService.delete(id);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("success", true);
        return resultMap;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteBatch")
    public Map<String, Object> deleteBatch(String ids) {
        String[] idsStr = ids.split(",");
        for (int i = 0; i < idsStr.length; i++) {
            resService.delete(Integer.parseInt(idsStr[i]));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("success", true);
        return resultMap;
    }

    /**
     * 查看次数加1
     *
     * @param id
     */
    @ResponseBody
    @RequestMapping("updateView")
    public void updateView(Integer id) {
        Res res = resService.getById(id);
        res.setView(res.getView() + 1);
        resService.save(res);
    }

    /**
     * 修改百度云分享链接
     *
     * @param res
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("updateShareLink")
    public Map<String, Object> updateShareLink(Res res, HttpSession session) {
        Map<String, Object> resultMap = new HashMap<>();
        if (CheckShareLinkEnableUtil.checkLink(res.getDownloadUrl())) {
            Res oldRes = resService.getById(res.getId());
            oldRes.setDownloadUrl(res.getDownloadUrl());
            oldRes.setDownloadPass(res.getDownloadPass());
            oldRes.setUseful(true);
            resService.save(oldRes);
            resultMap.put("success", true);

            User user = (User) session.getAttribute("currentUser");
            Res updateRes = new Res();
            updateRes.setUseful(false);
            updateRes.setUser(user);
            session.setAttribute("unUsefulResCount", resService.getTotal(updateRes));
            redisUtil.del("res_" + res.getId());
        } else {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "百度云分享链接已经失效 ，请重新发布");
        }
        return resultMap;
    }
}
